﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using KDG.FoldersSize.Scaner;
using System.Windows.Threading;

namespace KDG.FoldersSize
{
    /// <summary>
    /// Interaction logic for FindItemsControl.xaml
    /// </summary>
    public partial class FindItemsControl : UserControl
    {
        public ScannerItem RootNode { get; set; }

        public FindItemsControl()
        {
            this.InitializeComponent();
            lvItems.ItemsSource = new List<ScannerItem>();
        }

        private void btFind_Click(object sender, RoutedEventArgs e)
        {
            if (RootNode != null)
            {
                string mask = tbMask.Text;
                List<ScannerItem> list = new List<ScannerItem>();
                
                Action<ScannerItem, string> find = null;
                find = new Action<ScannerItem, string>((x, m) =>
                {
                    if (x.Name.Contains(m))
                        list.Add(x);
                    if (x.Childs != null)
                        x.Childs.ForEach(c => find(c, m));
                });
                find(RootNode, mask);

                lvItems.ItemsSource = list;

                this.Refresh();

                System.Windows.MessageBox.Show(
                    string.Format("Search completed. \r\nFind {0} item(s).", list.Count),
                    "[Search]kDg.Folders Size");
            }
        }


        internal void Refresh()
        {
            lvItems.Dispatcher.Invoke(DispatcherPriority.Render, new Action(() => { }));
        }

        private void OpenInExplorerClick(object sender, System.Windows.RoutedEventArgs e)
        {
            this.With(x => lvItems)
                .With(x => x.SelectedItem as ScannerItem)
                .Do(x => System.Diagnostics.Process.Start(x.FullName));

        }

        private void tbMaskKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
                btFind_Click(sender, null);
        }
    }
}